package tools;

import java.applet.Applet;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import abstracts.Screen;
import resources.Music;
import screens.LoadingScreen;

/** Displayed in browser. */
public class GameApplet extends Applet implements Runnable {
    /** Auto generated serial version UID. */
    private static final long serialVersionUID = -7120848176473722093L;

    /** The current {@linkplain Thread}. */
    private Thread thread;
    /** The current {@linkplain Screen}. */
    private Screen screen;
    /** */
    private Canvas canvas;
    /** */
    private BufferStrategy bufferStrategy;

    /** Begins a thread to run the game. */
    @Override
    public final void init() {
        thread = new Thread(this);
        thread.start();
    }

    /** Clean up resources. */
    @Override
    public final void destroy() {
        Music.set(null);
        setScreen(null);
    }

    @Override
    public final void run() {
        // Get our back buffer
        canvas = new Canvas();
        canvas.setSize(getSize());
        add(canvas);
        canvas.createBufferStrategy(2);
        bufferStrategy = canvas.getBufferStrategy();

        // Loads resources for the rest of the game
        setScreen(new LoadingScreen(this));

        // Keep running the screens until null screen is entered
        while (screen != null) {
            screen.run();
        }
    }

    /** @param drawMe - the screen to draw. */
    public final void draw(final Screen drawMe) {
        // Draw the screen to the back buffer
        Graphics backGraphics = bufferStrategy.getDrawGraphics();
        drawMe.draw(backGraphics);
        backGraphics.dispose();

        // Draw the back buffer to screen
        bufferStrategy.show();
    }

    /** @param newScreen - the new {@linkplain Screen}. */
    public final void setScreen(final Screen newScreen) {
        screen = newScreen;
    }

    /** @return the current {@linkplain Screen}. */
    public final Screen getScreen() {
        return screen;
    }

    /** @return the {@linkplain Canvas}. */
    public final Canvas getCanvas() {
        return canvas;
    }

    @Override
    public final void update(final Graphics g) {
        // Do nothing
    }
}
